package com.pb.service.boot.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域的设置问题
 * @author liudebao
 * @version v1.0.0
 */
@Order(1)
@WebFilter(urlPatterns = "/*",filterName = "ACAFilter")
public class ACAFilter implements Filter {

    /**
     * 初始化
     * @param filterConfig FilterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * 过滤
     * @param servletRequest
     * @param servletResponse
     * @param filterChain http://localhost:8080
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String hd = request.getHeader("Origin");
        if (StringUtils.isNotEmpty(hd)) {
            hd.replaceAll("\\r\\n","");
            hd.replaceAll("%0d%0a","");
            response.setHeader("Access-Control-Allow-Origin", hd);
        } else {
            response.setHeader("Access-Control-Allow-Origin", null);
        }
        response.setHeader("Access-Control-Expose-Headers", "X-forwared-port,X-forwarded-host");
        response.setHeader("Access-Control-expose-Headers", "Authorization,BiToken,Cookie");
        response.setHeader("Set-Cookie", "SameSite=None;Secure");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,Origin,Accept,Authorization,token,uc-token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("x-frame-options", "ALLOW-FROM http://127.0.0.1:8075/");
        filterChain.doFilter(new XSSRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
}
